# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
import json
import threading
import time
import odoo


class CustomerModel(models.Model):
    _name = 'customer.model'
    _description = '自定义模型'

    name = fields.Char(string='名称')
    width = fields.Float(string='宽度')
    height = fields.Float(string='高度')
    color = fields.Selection([('red', '红'), ('white', '白色'), ('green', '绿色')], string='颜色')
    date_start = fields.Datetime(string='开始时间', default=fields.Date.today())
    date_stop = fields.Datetime(string='停止时间', default=fields.Date.today())
    binary_ids = fields.Many2many('ir.attachment', 'cus_attachment_id', 'cus_id', 'attachment_id', '准备文件')
    files = fields.Many2one('file.file', string='附件')

    def button_css(self):
        """开启多线程搞事情"""
        for res in self:
            res.height += 10
        self.excute_threading_func()

    @api.model
    def excute_threading_func(self):
        """
        点击按钮，创建一个对象，执行线程方法，线程方法中等待时间后查出所有对象，并将对象的属性height增加5
        """
        model = self.env['customer.model']
        model.create({'name': 'test', 'width': 2})
        # 执行方法
        t1 = threading.Thread(target=self.stop_test, args=())
        t1.start()

    def stop_test(self):
        time.sleep(5)
        # 获取属性
        dbname = self.env.cr.dbname
        _context = self._context
        db_registry = odoo.registry(dbname)
        with api.Environment.manage(), db_registry.cursor() as cr:
            # 封装self
            new_cr = self.pool.cursor()
            env = api.Environment(cr, odoo.SUPERUSER_ID, _context)
            # self = self.with_env(env(cr=new_cr))
            # 查询对象修改值
            # result = self.env['customer.model'].search([])
            result = env['customer.model'].search([])
            for res in result:
                print(res, res.height)
                res.height += 5
                print(res, res.height)
        # 关闭cursor
        new_cr.close()

    @api.model
    def test(self):
        print('成功')

    @api.model
    def rpc_method(self, activeIds):
        return json.dumps({'data': 'aaaaaaaaaaa'})

    @api.model
    def create(self, vals_list):
        res = super(CustomerModel, self).create(vals_list)
        return res


class Files(models.Model):

    _name = 'file.file'

    file_name1213 = fields.Char('名称', size=64)
    binary_id = fields.Binary(string='主文件')
    file_name = fields.Char('Excel File', size=64)
    parent_id = fields.Many2one('file.file', string='上级')
    child_ids = fields.One2many('file.file', 'parent_id', string='下级')

    @api.model
    def to_baidu(self):
        action = {
            'type': 'ir.actions.act_url',
            'targe': 'new',
            'url': 'https://www.baidu.com/'
        }
        return action
